package com.doubao.doubao_admin.service.cService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.doubao.doubao_admin.model.entity.UmsUser;
import com.doubao.doubao_admin.mapper.UmsUserMapper;
import com.doubao.doubao_admin.model.dto.LoginDTO;
import com.doubao.doubao_admin.model.dto.RegisterDTO;
import com.doubao.doubao_admin.model.vo.ProfileVO;
import com.doubao.doubao_admin.utils.JwtUtils;
import com.doubao.doubao_admin.utils.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UmsUserService {
    @Resource
    private UmsUserMapper umsUserMapper;

    public int addUser(String username, String password) {
        UmsUser user = new UmsUser(username, password);
        int count = umsUserMapper.addUser(user);
        return count;
    }

    public List<UmsUser> queryByUsername(String username) {
        List<UmsUser> userList = umsUserMapper.queryByUsers(username);
        return userList;
    }

    /**
     * 注册对象
     *
     * @param dto
     * @return
     */
    public UmsUser executeRegister(RegisterDTO dto) throws NoSuchAlgorithmException {
        //查询是否有相同用户名的用户
        LambdaQueryWrapper<UmsUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UmsUser::getUsername, dto.getName());
        UmsUser umsUser = umsUserMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(umsUser)) {
            System.out.println("账号已存在！");
        }

        UmsUser addUser = UmsUser.builder()
                .username(dto.getName())
                .alias(dto.getName())
                .password(MD5.getMD5(dto.getPass()))
                .email(dto.getEmail())
                .createTime(new Date())
                .status(true)
                .build();
        umsUserMapper.insert(addUser);
        return addUser;
    }

    /**
     * 用户登录 生成JWT 的token
     * @param dto
     * @return
     */
    public String executeLogin(LoginDTO dto) {
        UmsUser user = umsUserMapper.queryByUsername(dto.getUsername());
        String encodePwd = MD5.getMD5(user.getPassword());

        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put("username", user.getUsername());
        map.put("password", user.getPassword());

        String token = JwtUtils.createToken(user.getUsername());

        return token;
    }

    /**
     * 获取用户信息
     * @param username
     * @return
     */
    public UmsUser getUserByUsername(String username) {
        UmsUser users = umsUserMapper.queryByUsername(username);
        return users;
    }

    public ProfileVO getUserProfile(String id){
        ProfileVO profileVO = umsUserMapper.getUserProfile(id);
        return profileVO;
    }
}
